import { createRouter, createWebHistory } from 'vue-router'
import { isLoggedIn } from '@/utils/auth'
import { ElMessage } from 'element-plus'

// 用户端路由
const userRoutes = {
  path: '/user',
  component: () => import('@/layouts/user/UserLayout.vue'),
  meta: { requiresAuth: true },
  children: [
    {
      path: 'home',
      name: 'Home',
      component: () => import('@/views/user/home/HomeView.vue'),
      meta: {
        title: '首页',
        requiresAuth: true
      }
    },
    {
      path: 'health',
      name: 'UserHealth',
      component: () => import('@/views/user/health/ProfileView.vue')
    },
    {
      path: 'growth',
      name: 'UserGrowth',
      component: () => import('@/views/user/growth/GrowthView.vue')
    },
    {
      path: 'consult',
      name: 'UserConsult',
      component: () => import('@/views/user/consult/ConsultView.vue')
    },
    {
      path: 'education',
      name: 'Education',
      component: () => import('@/views/user/education/EducationView.vue'),
      meta: {
        title: '健康科普',
        requiresAuth: true
      }
    },
    {
      path: 'profile',
      name: 'Profile',
      component: () => import('@/views/user/profile/ProfileView.vue'),
      meta: {
        title: '个人信息',
        requiresAuth: true
      }
    },
    {
      path: 'community',
      name: 'Community',
      component: () => import('@/views/user/community/CommunityView.vue'),
      meta: {
        title: '育儿社区',
        requiresAuth: true
      }
    },
    {
      path: 'selfcheck',
      name: 'Selfcheck',
      component: () => import('@/views/user/selfcheck/SelfcheckView.vue'),
      meta: {
        title: '自检助手',
        requiresAuth: true
      }
    },
    {
      path: 'hospitalNav',
      name: 'HospitalNav',
      component: () => import('@/views/user/hospitalNav/HospitalNavView.vue'),
      meta: {
        title: '医院导航',
        requiresAuth: true
      }
    },
    {
      path: 'assessment',
      name: 'Assessment',
      component: () => import('@/views/user/assessment/AssessmentView.vue'),
      meta: {
        title: '心理测评',
        requiresAuth: true
      }
    },
    {
      path: 'community/post/:id',
      name: 'PostDetail',
      component: () => import('@/views/user/community/PostDetail.vue'),
      meta: {
        title: '帖子详情',
        requiresAuth: true
      }
    },
    {
      path: 'settings',
      name: 'UserSettings',
      component: () => import('@/views/user/profile/UserSettingsView.vue'),
      meta: {
        title: '个人设置',
        requiresAuth: true
      }
    }
  ]
}

// 管理端路由
const adminRoutes = {
  path: '/admin',
  component: () => import('@/layouts/admin/AdminLayout.vue'),
  redirect: '/admin/dashboard',
  children: [
    {
      path: 'dashboard',
      name: 'AdminDashboard',
      component: () => import('@/views/admin/dashboard/DataAnalysisView.vue'),
      meta: { 
        title: '数据统计',
        requiresAuth: true,
        roles: ['admin']
      }
    },
    {
      path: 'users',
      name: 'UserManagement',
      component: () => import('@/views/admin/user/UserManagementView.vue'),
      meta: { title: '用户管理', requiresAuth: true, roles: ['admin'] }
    },
    {
      path: 'experts',
      name: 'ExpertManagement',
      component: () => import('@/views/admin/expert/ExpertManagementView.vue'),
      meta: { title: '专家管理', requiresAuth: true, roles: ['admin'] }
    },
    {
      path: 'science',
      name: 'ScienceManagement',
      component: () => import('@/views/admin/science/ScienceView.vue'),
      meta: { title: '科普管理', requiresAuth: true, roles: ['admin'] }
    }
  ]
}

// 登录路由
const loginRoute = {
  path: '/login',
  name: 'Login',
  component: () => import('@/views/login/LoginView.vue')
}

// 根路由重定向
const rootRoute = {
  path: '/',
  redirect: '/user/home'
}

// 专家端路由
const expertRoutes = {
  path: '/expert',
  component: () => import('@/layouts/expert/ExpertLayout.vue'),
  meta: { requiresAuth: true, requiresExpert: true },
  children: [
    {
      path: '',
      redirect: '/expert/consultation'
    },
    {
      path: 'consultation',
      name: 'ExpertConsultation',
      component: () => import('@/views/expert/consultation/ConsultationView.vue'),
      meta: {
        title: '咨询管理',
        requiresAuth: true,
        requiresExpert: true
      }
    }
  ]
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    rootRoute,
    userRoutes,
    expertRoutes,
    adminRoutes,
    loginRoute
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  console.log('路由守卫 - 目标路由:', to.path)
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    console.log('该路由需要认证')
    const isAuthenticated = isLoggedIn()
    console.log('是否已登录:', isAuthenticated)

    if (!isAuthenticated) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      // 获取用户角色
      const userRole = localStorage.getItem('userRole')
      console.log('当前用户角色:', userRole)
      
      // 检查是否需要专家权限
      if (to.matched.some(record => record.meta.requiresExpert)) {
        if (userRole !== 'expert') {
          console.log('无权访问专家页面')
          ElMessage.error('无权访问专家页面')
          next('/user/home')
          return
        }
      }
      
      // 检查是否需要管理员权限
      if (to.matched.some(record => record.meta.requiresAdmin)) {
        if (userRole !== 'admin') {
          console.log('无权访问管理员页面')
          ElMessage.error('无权访问管理员页面')
          next('/user/home')
          return
        }
      }
      
      next()
    }
  } else {
    next()
  }
})

export default router 